﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Clrizr.Web.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string color)
        {
            if (color == null
                || String.IsNullOrEmpty(color.Trim()))
            {
                return View();
            }

            color = color.ToUpper();

            //do SOME validation on the input to ensure it is a HEX code
            List<char> allowedVals = new List<char>() { 'A', 'B', 'C', 'E', 'D', 'F', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            if (
                !(color.Length == 7                                     //color isn't long enought 
                || color[0] == '#'                                      //color doesn't start with HEX value
                || color.Skip(1).Any(x => !allowedVals.Contains(x)))    //color contains non-hex chars...
                )
            {
                return View();
            }

            var colors = Server.MapPath("~/styles/colors.less");

            var colorsdef = System.IO.File.ReadAllLines(colors);

            if (!colorsdef[0].Contains("@clrizr-input"))
                return View();

            colorsdef[0] = String.Format("@clrizr-input: {0};", color);

            System.IO.File.WriteAllLines(colors, colorsdef);

            return View();
        }
    }
}